// 自动导入所有子模块

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const routerPush = Router.prototype.push
Router.prototype.push = function push (location) {
    return routerPush.call(this, location).catch(error => error)
}
let routes = [
    {
        path: '/setting',
        component: () => import('@/views/global/index.vue'),
        children: [
            {
                path: 'menu',
                component: () => import('@/views/setting/menu'),
                meta: { title: '菜单管理' }
            },
            {
                path: 'users',
                component: () => import('@/views/setting/users'),
                meta: { title: '用户管理' }
            },
            {
                path: 'userGroup',
                component: () => import('@/views/setting/userGroup'),
                meta: { title: '用户组管理' }
            }
        ]
    },
    {
        path: '*',
        redirect: '/hello'
    }
]
const routerContext = require.context('./', true, /index\.js$/)
routerContext.keys().forEach(route => {
    // 如果是根目录的 index.js 、不处理
    if (route.startsWith('./index.js')) {
        return
    }
    const routerModule = routerContext(route)
    /**
   * 兼容 import export 和 require module.export 两种规范
   */
    routes = [...(routerModule.default || routerModule), ...routes]
})
let ro = new Router({
    mode: 'history',
    base: 'work',
    routes
})

ro.beforeEach((to, from, next) => {
    if (to.meta.title) {
        document.title = to.meta.title
    }
    if (!window.localStorage.getItem('userInfo') && to.path !== '/login') {
        next('/login')
    } else {
        next()
    }
})

export default ro
